package org.openfans.rss;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

/**
 * 描述：<br>
 * 日期：2006-5-29<br>
 * 
 * @author 张俊<br>
 * @email:pesome@gmail.com<br>
 */
public class FeedServlet extends HttpServlet {
	private static final String DEFAULT_FEED_TYPE = "default.feed.type";

	private static final String FEED_TYPE = "type";

	private static final String MIME_TYPE = "application/xml; charset=UTF-8";

	private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";

	private String _defaultFeedType;

	public void init() {
		_defaultFeedType = getServletConfig().getInitParameter(
				DEFAULT_FEED_TYPE);
		_defaultFeedType = (_defaultFeedType != null) ? _defaultFeedType
				: "rss_2.0";
	}

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		try {
			SyndFeed feed = getRssWriter().getFeed(DEFAULT_FEED_TYPE);

			String feedType = req.getParameter(FEED_TYPE);
			feedType = (feedType != null) ? feedType : _defaultFeedType;
			feed.setFeedType(feedType);

			res.setContentType(MIME_TYPE);
			SyndFeedOutput output = new SyndFeedOutput();
			output.output(feed, res.getWriter());
		} catch (FeedException ex) {
			String msg = COULD_NOT_GENERATE_FEED_ERROR;
			log(msg, ex);
			res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
		}
	}

	private RssWriter getRssWriter() {
		return (RssWriter) WebApplicationContextUtils.getWebApplicationContext(
				getServletConfig().getServletContext()).getBean("rssWriter");
	}

}
